package com.mm.cloud.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.cloud.common.core.enums.DeleteEnum;
import com.mm.cloud.common.core.exception.BaseException;
import com.mm.cloud.common.core.result.Result;
import com.mm.cloud.common.core.result.ResultConstants;
import com.mm.cloud.common.core.result.ResultUtil;
import com.mm.cloud.common.security.annotation.ParameterCheck;
import com.mm.cloud.common.security.helper.LoginUserHelper;
import com.mm.cloud.common.security.loginuser.LoginUser;
import com.mm.cloud.sys.dto.form.RoleDTO;
import com.mm.cloud.sys.dto.form.RoleToPermissionDTO;
import com.mm.cloud.sys.dto.query.QueryRoleDTO;
import com.mm.cloud.sys.entity.Role;
import com.mm.cloud.sys.mapper.RoleMapper;
import com.mm.cloud.sys.service.IRoleService;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色基础信息 服务实现类
 * </p>
 *
 * @author mr
 * @since 2020-09-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Override
    public Result<List<Role>> getRoleList(QueryRoleDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        dto.setCompanyId(loginUser.getCompanyId());
        IPage<Role> page = this.baseMapper.getRoleList(new Page<>(dto.getPage(), dto.getLimit()), dto);
        return ResultUtil.success(page.getRecords(), page.getTotal());
    }

    @Override
    @ParameterCheck
    public Result<String> saveRole(RoleDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        // 校验角色名称
        Role existRole = this.getOne(Wrappers.<Role>lambdaQuery()
                .eq(Role::getCompanyId, loginUser.getCompanyId())
                .eq(Role::getRoleName, dto.getRoleName())
                .eq(Role::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.nonNull(existRole)) {
            return ResultUtil.fail("角色名称已使用");
        }
        // 校验编码名称
        existRole = this.getOne(Wrappers.<Role>lambdaQuery()
                .eq(Role::getCompanyId, loginUser.getCompanyId())
                .eq(Role::getRoleCode, dto.getRoleCode())
                .eq(Role::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.nonNull(existRole)) {
            return ResultUtil.fail("角色编码已使用");
        }
        Role role = new Role();
        BeanUtils.copyProperties(dto, role);
        role.setCompanyId(loginUser.getCompanyId());
        role.setCreaterId(loginUser.getUserId());
        role.setCreateTime(LocalDateTime.now());
        role.setIsDelete(DeleteEnum.NOT_DELETE.getStatus());
        this.save(role);
        return ResultUtil.success();
    }

    @Override
    @ParameterCheck
    public Result<String> updateRole(RoleDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        Role role = this.getRoleAssert(loginUser.getCompanyId(), dto.getId());
        // 校验角色名称
        Role existRole = this.getOne(Wrappers.<Role>lambdaQuery()
                .eq(Role::getCompanyId, loginUser.getCompanyId())
                .eq(Role::getRoleName, dto.getRoleName())
                .eq(Role::getIsDelete, DeleteEnum.NOT_DELETE.getStatus())
                .ne(Role::getId, dto.getId()));
        if (Objects.nonNull(existRole)) {
            return ResultUtil.fail("角色名称已使用");
        }
        // 校验编码名称
        existRole = this.getOne(Wrappers.<Role>lambdaQuery()
                .eq(Role::getCompanyId, loginUser.getCompanyId())
                .eq(Role::getRoleCode, dto.getRoleCode())
                .eq(Role::getIsDelete, DeleteEnum.NOT_DELETE.getStatus())
                .ne(Role::getId, dto.getId()));
        if (Objects.nonNull(existRole)) {
            return ResultUtil.fail("角色编码已使用");
        }
        BeanUtils.copyProperties(dto, role);
        role.setUpdaterId(loginUser.getUserId());
        role.setUpdateTime(LocalDateTime.now());
        this.updateById(role);
        return ResultUtil.success();
    }

    @Override
    public Result<String> deleteRole(Long roleId) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        Role role = this.getRoleAssert(loginUser.getCompanyId(), roleId);
        role.setUpdaterId(loginUser.getUserId());
        role.setUpdateTime(LocalDateTime.now());
        role.setIsDelete(DeleteEnum.DELETE.getStatus());
        this.updateById(role);
        return ResultUtil.success();
    }

    @Override
    @ParameterCheck
    public Result<List<Long>> getPermissionIdByRoleId(@NotNull(message = "参数不能为空") Long roleId) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        return ResultUtil.success(this.baseMapper.getPermissionIdByRoleId(loginUser.getCompanyId(), roleId));
    }

    @Override
    @ParameterCheck
    @Transactional
    public Result<String> setRoleToPermission(RoleToPermissionDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        this.baseMapper.deleteRoleToPermission(loginUser.getCompanyId(), dto.getRoleId());
        if (!StringUtils.isEmpty(dto.getPermissionIds())) {
            this.baseMapper.setRoleToPermission(loginUser.getCompanyId(), dto.getRoleId(), Arrays.stream(dto.getPermissionIds().split(",")).map(Long::parseLong).collect(Collectors.toList()));
        }
        return ResultUtil.success();
    }

    /**
     * 查询角色信息
     *
     * @param companyId 公司ID
     * @param roleId    角色ID
     * @return Role
     */
    private Role getRoleAssert(Long companyId, Long roleId) {
        Assert.notNull(companyId, "companyId is null");
        Assert.notNull(roleId, "userId is null");
        Role role = this.getOne(Wrappers.<Role>lambdaQuery().eq(Role::getCompanyId, companyId).eq(Role::getId, roleId).eq(Role::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.isNull(role)) {
            throw new BaseException(ResultConstants.QUERY_NOT_FOUND_DATA);
        }
        return role;
    }
}
